package com.gzz.orchid.common.core.util;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * 解析IP地址工具
 *
 * @author higmd
 */
@Slf4j
public class IPUtil {
    private static final String UNKNOWN = "unknown";

    /**
     * 获取IP地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        // 通过nginx获取ip
        String ip = request.getHeader("x-forwarded-for");
        // k8s将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Original-Forwarded-For");
        }
        // 通过Apache代理获取ip
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        // 通过WebLogic代理获取ip
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        // 通过负载均衡获取IP地址（HTTP_CLIENT_IP、HTTP_X_FORWARDED_FOR）
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        // 通过Nginx获取ip（Nginx中的另一个变量，内容就是请求中X-Forwarded-For的信息）
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //兼容集群获取ip
        if (StringUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            // 客户端和服务器为同一台机器时，获取的地址为IPV6格式："0:0:0:0:0:0:0:1"
            //if ("127.0.0.1".equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
            if (Arrays.asList("127.0.0.1", "0:0:0:0:0:0:0:1").contains(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                    ip = iNet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("根据网卡获取IP地址异常: ", e);
                }
            }
        }
        //使用代理，则获取第一个IP地址为客户端的真实IP
        if (ip != null && ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
            ip = ip.split(",")[0];
        }

        return ip;
    }

    /**
     * 获取IP归属地
     * 备注：并发使用，每个线程需要创建一个独立的 searcher 对象单独使用。
     */
    public static String getRegion(String ip) {
        try (InputStream in = IPUtil.class.getClassLoader().getResourceAsStream("ip2region.xdb")) {
            // String dbPath = IPUtil.class.getClassLoader().getResource("ip2region.xdb").getFile();
            if (in != null) {
                Searcher searcher = Searcher.newWithBuffer(in.readAllBytes());
                //Searcher searcher = Searcher.newWithFileOnly(dbPath);
                long sTime = System.nanoTime();
                String regionInfo = searcher.search(ip);
                System.out.printf("regionInfo : %s, \n", regionInfo);
                String region = formatInfo(regionInfo);
                long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
                log.info("{IP属地 : {}, ip: {}}, 耗时: {} 纳秒}", region, ip, cost);
                return region;
            } else {
                log.error("获取IP地址失败");
                return null;
            }
        } catch (Exception e) {
            log.error("IP地址异常 ({}) : {}\n", ip, e.getMessage());
            return null;
        }
    }

    /**
     * 解析城市信息，国内显示城市名，国外显示国家名
     */
    private static String formatInfo(String regionInfo) {
        if (!StringUtil.isEmpty(regionInfo)) {
            //            if (cityArr.length > 0) {
            //                if ("内网ip".equalsIgnoreCase(cityArr[0])) {return "内网IP";}
            //                if ("中国".equals(cityArr[0])) {return cityArr[1];}
            //                return cityArr[0];
            //            }
            return regionInfo
                    .replace("|0", "")
                    .replace("0|", "")
                    .replace("|", ",");
        }
        return "未知IP";
    }

    /**
     * 获取浏览器信息
     */
    public static String getUserAgent(HttpServletRequest request) {
        return request.getHeader("user-agent");
    }


    public static void main(String[] args) {
        //System.out.println(getRegion("182.242.185.133"));
    }


    /**
     * 获取复杂网络环境下的Ip地址
     */
    public InetAddress getLocalHostLanAddress() throws Exception {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration<?> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            return InetAddress.getLocalHost();
        } catch (Exception e) {
            log.error("获取IP地址异常: ", e);
        }
        return null;
    }

}